//
//  GRContactCertificationViewController.m
//  YC_GRice
//
//  Created by LiuFeng on 2018/7/23.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRContactCertificationViewController.h"
//#import "GRPayDetailViewController.h"

#import "GRCertificationHeader.h"
#import "GRCertificationFooter.h"
#import "GRContactHeader.h"
#import "GRContactCertificationViewCell.h"

@interface GRContactCertificationViewController () <GRCertificationProtocol>

@property (nonatomic, strong) GRCertificationFooter *footer;

@property (nonatomic, strong) NSMutableDictionary *resultDic;

@end

@implementation GRContactCertificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self checkAuthorization];
    // Uncomment the following line to preserve selection between presentations.
    GRCertificationHeader *header  = [[GRCertificationHeader alloc] initWithCertification:GRCertificationContact];
    self.tableView.tableHeaderView = header;
    self.tableView.tableFooterView = self.footer;
    self.tableView.backgroundColor = HEXCOLOR(0xf8f8f8);
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    [self.tableView registerNib:[UINib nibWithNibName:@"GRContactCertificationViewCell" bundle:nil] forCellReuseIdentifier:@"GRContactCertificationViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"GRContactHeader" bundle:nil] forHeaderFooterViewReuseIdentifier:@"GRContactHeader"];
}

/**
 检查通讯录授权
 */
- (void)checkAuthorization {
    if (@available(iOS 9.0, *)) {
        CNContactStore *contactStore = [[CNContactStore alloc] init];
        if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusNotDetermined) {
            [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                NSLog(@"%d %@",granted, error);
            }];
        }else if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] != CNAuthorizationStatusAuthorized) {
            [[LFAlertBox defaultAlert] showAlertTitle:@"提示" content:@"请到设置>隐私>通讯录打开本应用的权限设置" cancleText:@"取消" sureText:@"去设置" completion:^(NSInteger index) {
                if (index == 1) {
                    [NSObject openSystemURL:UIApplicationOpenSettingsURLString];
                }
            }];
        }
    } else {
        // Fallback on earlier versions
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
        ABAuthorizationStatus authStatus = ABAddressBookGetAuthorizationStatus();
        if (authStatus == kABAuthorizationStatusNotDetermined) {
            ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
                NSLog(@"%d %@",granted, error);
            });
        }else if (authStatus != kABAuthorizationStatusAuthorized) {
            [[LFAlertBox defaultAlert] showAlertTitle:@"提示" content:@"请到设置>隐私>通讯录打开本应用的权限设置" cancleText:@"取消" sureText:@"去设置" completion:^(NSInteger index) {
                if (index == 1) {
                    [NSObject openSystemURL:UIApplicationOpenSettingsURLString];
                }
            }];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GRContactCertificationViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GRContactCertificationViewCell" forIndexPath:indexPath];
    cell.currentVc = self;
    cell.delegate  = self;
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    GRContactHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"GRContactHeader"];
    [header contactPersonAtSection:section];
    return header;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 45;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return section == 0 ? 10 : 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90;
}

#pragma Mark  =================   GRCertificationProtocol   ===============

-(void)didselectConfirmAction:(UIButton *)sender {
    sender.enabled = NO;
    
    GRContactHeader *relativesHeader = (GRContactHeader *)[self.tableView headerViewForSection:0];
    GRContactCertificationViewCell *relativesCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    NSDictionary *relativesParamer   = @{@"name"  : relativesCell.realNameTF.text,
                                         @"phone" : relativesCell.mobileTF.text,
                                         @"type"  : @(relativesHeader.type)
                                         };
    
    GRContactHeader *friendHeader = (GRContactHeader *)[self.tableView headerViewForSection:1];
    GRContactCertificationViewCell *friendCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    NSDictionary *friendParamer   = @{@"name"  : friendCell.realNameTF.text,
                                      @"phone" : friendCell.mobileTF.text,
                                      @"type"  : @(friendHeader.type+3)
                                      };
    NSDictionary *paramer = @{@"paramList" : @[relativesParamer, friendParamer]};
    
    [GRCertificationAction addAnEmergencyContact:paramer completionHandler:^(BOOL success, id responseObject, GRError *error) {
        if (success) {
            BOOL ispass = NO;
            if (responseObject[@"isPass"]) {
                ispass  = [responseObject[@"isPass"] boolValue];
            }
            [self goBackDesignatedController:ispass];
        }else {
            [GRHUD showMessage:error.errorMsg atView:self.view];
        }
        sender.enabled = YES;
    }];
}

- (void)goBackDesignatedController:(BOOL)isAuth {
    BOOL isBackToPay     = NO; NSInteger index = 0;
    for (UIViewController *vc in self.navigationController.viewControllers) {

    }
    
    if (isBackToPay && isAuth) {

    }else {
        [self.navigationController popViewControllerAnimated:YES];
        if (self.refreshBlock) {
            self.refreshBlock();
        }
    }
}


-(void)didselectContactPerson:(BOOL)isFinish AtCell:(UITableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSString *key          = [NSString stringWithFormat:@"%ld-%ld",indexPath.row, indexPath.section];
    
    isFinish ? [self.resultDic setValue:cell forKey:key] : [self.resultDic removeObjectForKey:key];
    
    self.resultDic.allKeys.count == 2 ? [self changeNextBtnStatus:YES] : [self changeNextBtnStatus:NO];
}


- (void)changeNextBtnStatus:(BOOL)next {
    _footer.sureBtn.enabled = next;
    _footer.sureBtn.backgroundColor = next ? KGMTHEM_COLOR : HEXCOLOR(0xeeeeee);
    [_footer.sureBtn setTitleColor:next ? KGMBLACK_COLOR : HEXCOLOR(0x999999) forState:UIControlStateNormal];
}


/**
 懒加载

 @return <#return value description#>
 */
-(GRCertificationFooter *)footer {
    if (!_footer) {
        _footer = [[GRCertificationFooter alloc] initWithFrame:CGRectMake(0, 0, KscreenWidth, 65)];
        _footer.delegate = self;
        [self changeNextBtnStatus:NO];
        [_footer.sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    }
    return _footer;
}

-(NSMutableDictionary *)resultDic {
    if (!_resultDic) {
        _resultDic = [NSMutableDictionary dictionary];
    }
    return _resultDic;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
